define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        // 入库单列表
        index: function () {
            Table.api.init({
                extend: {
                    index_url: 'scanwork/inventory_management/index' + location.search,
                    add_url: 'scanwork/inventory_management/add',
                    edit_url: 'scanwork/inventory_management/edit',
                    del_url: 'scanwork/inventory_management/del',
                    multi_url: 'scanwork/inventory_management/multi',
                    table: 'scanwork_purchase_inbound',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'inbound_no', title: '入库单号', operate: 'LIKE'},
                        {field: 'supplier_name', title: '供应商', operate: 'LIKE'},
                        {field: 'warehouse_name', title: '仓库', operate: 'LIKE'},
                        {field: 'inbound_date', title: '入库日期', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'total_amount', title: '总金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'operator_name', title: '操作员', operate: 'LIKE'},
                        {field: 'status', title: '状态', searchList: {0:'草稿',1:'待入库',2:'已入库',3:'已取消'}, formatter: function(value, row, index) {
                            var statusMap = {
                                0: {text: '草稿', class: 'default'},
                                1: {text: '待入库', class: 'warning'},
                                2: {text: '已入库', class: 'success'},
                                3: {text: '已取消', class: 'danger'}
                            };
                            var status = statusMap[value] || {text: '未知', class: 'default'};
                            return '<span class="label label-' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'createtime', title: '创建时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: '明细',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-eye',
                                    url: 'scanwork/inventory_management/detail',
                                    extend: 'data-area=\'["90%","90%"]\'',
                                }
                            ]
                        }
                    ]
                ]
            });

            Table.api.bindevent(table);
            
            // 批量审核通过按钮事件
            $(document).on('click', '.btn-batch-approve', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要审核的入库单');
                    return;
                }
                
                Layer.confirm('确定要批量审核通过选中的入库单吗？', function(index) {
                    batchOperation('approve', ids);
                    Layer.close(index);
                });
            });
            
            // 批量审核拒绝按钮事件
            $(document).on('click', '.btn-batch-reject', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.warning('请选择要审核的入库单');
                    return;
                }
                
                Layer.confirm('确定要批量审核拒绝选中的入库单吗？', function(index) {
                    batchOperation('reject', ids);
                    Layer.close(index);
                });
            });
        },

        // 入库审核
        audit: function () {
            Controller.api.bindevent();
            
            // 全选/取消全选
            $('#select-all').on('change', function() {
                $('.inbound-checkbox').prop('checked', $(this).prop('checked'));
            });
            
            // 单个选择时更新全选状态
            $('.inbound-checkbox').on('change', function() {
                var totalCheckboxes = $('.inbound-checkbox').length;
                var checkedCheckboxes = $('.inbound-checkbox:checked').length;
                $('#select-all').prop('checked', totalCheckboxes === checkedCheckboxes);
            });
            
            // 表单提交
            $('#audit-form').on('submit', function(e) {
                e.preventDefault();
                
                var selectedIds = [];
                $('.inbound-checkbox:checked').each(function() {
                    selectedIds.push($(this).val());
                });
                
                if (selectedIds.length === 0) {
                    Toastr.warning('请选择要审核的入库单');
                    return;
                }
                
                var auditResult = $('input[name="audit_result"]:checked').val();
                if (!auditResult) {
                    Toastr.warning('请选择审核结果');
                    return;
                }
                
                var auditRemark = $('textarea[name="audit_remark"]').val();
                
                Layer.confirm('确定要提交审核吗？', function(index) {
                    $.ajax({
                        url: 'scanwork/inventory_management/audit',
                        type: 'POST',
                        data: {
                            ids: selectedIds,
                            audit_result: auditResult,
                            audit_remark: auditRemark
                        },
                        dataType: 'json',
                        success: function(data) {
                            Layer.close(index);
                            if (data.code == 1) {
                                Toastr.success(data.msg || '审核完成');
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                Toastr.error(data.msg || '审核失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            Layer.close(index);
                            Toastr.error('审核失败：' + error);
                        }
                    });
                });
            });
        },

        // 入库统计
        statistics: function () {
            Controller.api.bindevent();
            
            // 生成统计按钮事件
            $('#btn-generate-statistics').on('click', function() {
                var formData = $('#statistics-form').serialize();
                
                $.ajax({
                    url: 'scanwork/inventory_management/statistics',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(data) {
                        if (data.code == 1) {
                            updateStatisticsDisplay(data.data);
                        } else {
                            Toastr.error(data.msg || '获取统计数据失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        Toastr.error('获取统计数据失败：' + error);
                    }
                });
            });
            
            // 页面加载时自动生成统计
            $('#btn-generate-statistics').trigger('click');
        },

        // 入库明细
        detail: function () {
            Controller.api.bindevent();
        },

        // 入库报表
        report: function () {
            Controller.api.bindevent();
            
            // 生成报表按钮事件
            $('#btn-generate-report').on('click', function() {
                var formData = $('#report-form').serialize();
                
                $.ajax({
                    url: 'scanwork/inventory_management/report',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(data) {
                        if (data.code == 1) {
                            updateReportDisplay(data.data, $('select[name="report_type"]').val());
                        } else {
                            Toastr.error(data.msg || '生成报表失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        Toastr.error('生成报表失败：' + error);
                    }
                });
            });
            
            // 导出Excel按钮事件
            $('#btn-export-report').on('click', function() {
                var formData = $('#report-form').serialize();
                var reportType = $('select[name="report_type"]').val();
                var startDate = $('input[name="start_date"]').val();
                var endDate = $('input[name="end_date"]').val();
                
                var url = 'scanwork/inventory_management/exportReport?' + formData;
                window.open(url, '_blank');
            });
            
            // 页面加载时自动生成报表
            $('#btn-generate-report').trigger('click');
        },

        // 批量操作
        batchOperation: function () {
            Controller.api.bindevent();
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    // 批量操作函数
    function batchOperation(operation, ids) {
        $.ajax({
            url: 'scanwork/inventory_management/batchOperation',
            type: 'POST',
            data: {
                ids: ids,
                operation: operation
            },
            dataType: 'json',
            success: function(data) {
                if (data.code == 1) {
                    Toastr.success(data.msg || '批量操作完成');
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    Toastr.error(data.msg || '批量操作失败');
                }
            },
            error: function(xhr, status, error) {
                Toastr.error('批量操作失败：' + error);
            }
        });
    }

    // 更新统计显示
    function updateStatisticsDisplay(data) {
        // 更新总体统计
        $('#total-count').text(data.total_stats.total_count || 0);
        $('#total-amount').text('¥' + parseFloat(data.total_stats.total_amount || 0).toFixed(2));
        $('#avg-amount').text('¥' + parseFloat(data.total_stats.avg_amount || 0).toFixed(2));
        
        var startDate = $('input[name="start_date"]').val();
        var endDate = $('input[name="end_date"]').val();
        $('#period-range').text(startDate + ' 至 ' + endDate);
        
        // 更新供应商统计
        var supplierTableBody = $('#supplier-stats-table tbody');
        supplierTableBody.empty();
        if (data.supplier_stats && data.supplier_stats.length > 0) {
            $.each(data.supplier_stats, function(index, item) {
                var row = '<tr>' +
                    '<td>' + (item.supplier_name || '未知供应商') + '</td>' +
                    '<td>' + (item.inbound_count || 0) + '</td>' +
                    '<td>¥' + parseFloat(item.total_amount || 0).toFixed(2) + '</td>' +
                    '</tr>';
                supplierTableBody.append(row);
            });
        } else {
            supplierTableBody.append('<tr><td colspan="3" class="text-center">暂无数据</td></tr>');
        }
        
        // 更新仓库统计
        var warehouseTableBody = $('#warehouse-stats-table tbody');
        warehouseTableBody.empty();
        if (data.warehouse_stats && data.warehouse_stats.length > 0) {
            $.each(data.warehouse_stats, function(index, item) {
                var row = '<tr>' +
                    '<td>' + (item.warehouse_name || '未知仓库') + '</td>' +
                    '<td>' + (item.inbound_count || 0) + '</td>' +
                    '<td>¥' + parseFloat(item.total_amount || 0).toFixed(2) + '</td>' +
                    '</tr>';
                warehouseTableBody.append(row);
            });
        } else {
            warehouseTableBody.append('<tr><td colspan="3" class="text-center">暂无数据</td></tr>');
        }
        
        // 更新日期统计
        var dailyTableBody = $('#daily-stats-table tbody');
        dailyTableBody.empty();
        if (data.daily_stats && data.daily_stats.length > 0) {
            $.each(data.daily_stats, function(index, item) {
                var row = '<tr>' +
                    '<td>' + (item.date || '') + '</td>' +
                    '<td>' + (item.inbound_count || 0) + '</td>' +
                    '<td>¥' + parseFloat(item.total_amount || 0).toFixed(2) + '</td>' +
                    '</tr>';
                dailyTableBody.append(row);
            });
        } else {
            dailyTableBody.append('<tr><td colspan="3" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新报表显示
    function updateReportDisplay(data, reportType) {
        var thead = $('#report-thead');
        var tbody = $('#report-tbody');
        
        thead.empty();
        tbody.empty();
        
        if (reportType == 'summary') {
            // 汇总报表
            thead.html('<tr>' +
                '<th>入库单号</th>' +
                '<th>供应商</th>' +
                '<th>入库日期</th>' +
                '<th>总金额</th>' +
                '<th>状态</th>' +
                '</tr>');
            
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    var statusText = '';
                    var statusClass = '';
                    switch(item.status) {
                        case 0:
                            statusText = '草稿';
                            statusClass = 'default';
                            break;
                        case 1:
                            statusText = '待入库';
                            statusClass = 'warning';
                            break;
                        case 2:
                            statusText = '已入库';
                            statusClass = 'success';
                            break;
                        case 3:
                            statusText = '已取消';
                            statusClass = 'danger';
                            break;
                    }
                    
                    var row = '<tr>' +
                        '<td>' + (item.inbound_no || '') + '</td>' +
                        '<td>' + (item.supplier_name || '') + '</td>' +
                        '<td>' + (item.inbound_date ? new Date(item.inbound_date * 1000).toLocaleDateString() : '') + '</td>' +
                        '<td>¥' + parseFloat(item.total_amount || 0).toFixed(2) + '</td>' +
                        '<td><span class="label label-' + statusClass + '">' + statusText + '</span></td>' +
                        '</tr>';
                    tbody.append(row);
                });
            } else {
                tbody.append('<tr><td colspan="5" class="text-center">暂无数据</td></tr>');
            }
        } else if (reportType == 'material') {
            // 物料入库报表
            thead.html('<tr>' +
                '<th>入库单号</th>' +
                '<th>物料名称</th>' +
                '<th>物料编码</th>' +
                '<th>供应商</th>' +
                '<th>入库日期</th>' +
                '<th>实际数量</th>' +
                '<th>单价</th>' +
                '<th>总金额</th>' +
                '</tr>');
            
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    var row = '<tr>' +
                        '<td>' + (item.inbound_no || '') + '</td>' +
                        '<td>' + (item.material_name || '') + '</td>' +
                        '<td>' + (item.material_code || '') + '</td>' +
                        '<td>' + (item.supplier_name || '') + '</td>' +
                        '<td>' + (item.inbound_date ? new Date(item.inbound_date * 1000).toLocaleDateString() : '') + '</td>' +
                        '<td>' + (item.actual_quantity || 0) + '</td>' +
                        '<td>¥' + parseFloat(item.unit_price || 0).toFixed(2) + '</td>' +
                        '<td>¥' + parseFloat(item.total_amount || 0).toFixed(2) + '</td>' +
                        '</tr>';
                    tbody.append(row);
                });
            } else {
                tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
            }
        }
    }

    return Controller;
});
